/*
 * FloatMap.cpp
 *
 *  Created on: Oct 5, 2012
 *      Author: burek
 */

#include <cstdlib>
#include <cstring>
#include <cstdio>

#include "FloatMap.h"
#include "math/util.h"

//#define _DEBUG

FloatMap::FloatMap(Uint32 Width, Uint32 Height)
{
	width = Width;
	height = Height;
	data = (float*)malloc(width * height * sizeof(float));
}

FloatMap::~FloatMap()
{
	free(data);
}

void FloatMap::pset(Uint32 x, Uint32 y, float texel)
{
#ifdef _DEBUG
	if(x >= 0 && y >= 0 && x < width && y < height) {
#endif
		data[x + y * width] = texel;
#ifdef _DEBUG
	}
#endif
}

float FloatMap::pget(Uint32 x, Uint32 y) const
{
#ifdef _DEBUG
	if(x >= 0 && y >= 0 && x < width && y < height) {
#endif
		return data[x + y * width];
#ifdef _DEBUG
	}
	else
	{
		return 0.0f;
	}
#endif
}

float FloatMap::singleSample(float x, float y) const
{
	Uint32 X = (Uint32)x;
	Uint32 Y = (Uint32)y;
	Uint32 X1 = X % width;
	Uint32 Y1 = Y % height;
	Uint32 X2 = (X + 1) % width;
	Uint32 Y2 = (Y + 1) % height;
	float u = x - (int)X;
	float v = y - (int)Y;
	return LERP(LERP(data[X1 + Y1 * width], data[X2 + Y1 * width], u),
			LERP(data[X1 + Y2 * width], data[X2 + Y2 * width], u), v);
}

float FloatMap::reSample(float x, float y, float multi, float intensity) const
{
	float s1 = singleSample(x, y);

	float X = x * multi;
	float Y = y * multi;

	X -= ((int)X / width) * width;
	Y -= ((int)Y / height) * height;

	float s2 = singleSample(X, Y);
	return s1 + s2 * intensity;
}

void FloatMap::clear()
{
	memset(data, 0, width * height * sizeof(float));
}

float FloatMap::getMin() const
{
	float x = data[0];
	for(int i = 1; i < width * height; ++i)
		x = rMin(x, data[i]);
	return x;
}

float FloatMap::getMax() const
{
	float x = data[0];
	for(int i = 1; i < width * height; ++i)
		x = rMax(x, data[i]);
	return x;
}


